package com.axend.aerosense.common.util;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;


import com.axend.aerosense.base.utils.ThreadPoolUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.tencent.tpns.baseapi.base.logger.DeviceInfo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;


/**
 * @author chenjiasheng
 * @description 网络图片保存到本地工具(兼容android 10 以上)
 * @time 2023/5/12 10:37
 */
public class ImageSaveUtil {


    /**
     * @param oldUri  原路径
     * @param context 上下文
     * @param bitmap  需要保存的bitmap
     * @param format  图片格式
     * @param quality 压缩比 如果图片是png格式则压缩比参数无用,100表示不压缩
     * @param recycle 完成以后是否回收bitmap
     * @return
     */
    public static Uri saveLocal(Context context, Uri oldUri, Bitmap bitmap, String fileName, Bitmap.CompressFormat format, int quality, boolean recycle) {
        String suffix;
        if (Bitmap.CompressFormat.JPEG == format)
            suffix = "JPG";
        else
            suffix = format.name();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            if (!isGranted()) {
                Log.e("ImageUtils", "save to album need storage permission");
                return null;
            }
            /*获取文件存储绝对路径*/
            File picDir = new File(getImageFileDes());
            File destFile = new File(picDir, fileName);
            if (!save(bitmap, destFile, format, quality, recycle))
                return null;
            Uri uri = null;
            if (destFile.exists()) {
                uri = Uri.parse("file://" + destFile.getAbsolutePath());
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(uri);
                context.sendBroadcast(intent);
            }
            return uri;
        } else {
            // Android 10 使用
            Uri contentUri;
            //判断是否有SD卡
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else
                contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "aerosense");
            // 告诉系统，文件还未准备好，暂时不对外暴露
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
            Cursor cursor = null;
            if (oldUri != null)
                cursor = context.getContentResolver().query(oldUri, null, null, null);
            Uri uri = null;
            if (cursor == null || cursor.getCount() == 0)
                uri = context.getContentResolver().insert(contentUri, contentValues);
            else
                uri = oldUri;
            if (uri == null) return null;
            OutputStream os = null;
            try {
                os = context.getContentResolver().openOutputStream(uri);
                bitmap.compress(format, quality, os);
                // 告诉系统，文件准备好了，可以提供给外部了
                contentValues.clear();
                contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
                context.getContentResolver().update(uri, contentValues, null, null);
                return uri;
            } catch (Exception e) {
                e.printStackTrace();
                // 失败的时候，删除此 uri 记录
                context.getContentResolver().delete(uri, null, null);
                return null;
            } finally {
                try {
                    if (os != null)
                        os.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }

    }


    private static boolean save(Bitmap bitmap, File file, Bitmap.CompressFormat format, int quality, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            Log.e("ImageUtils", "bitmap is empty.");
            return false;
        }
        if (bitmap.isRecycled()) {
            Log.e("ImageUtils", "bitmap is recycled.");
            return false;
        }
        if (!createFile(file, true)) {
            Log.e("ImageUtils", "create or delete file <$file> failed.");
            return false;
        }
        OutputStream os = null;
        boolean ret = false;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            ret = bitmap.compress(format, quality, os);
            if (recycle && !bitmap.isRecycled()) bitmap.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                // ignore
            }
        }
        return ret;
    }

    /**
     * 判断bitmap有无被回收
     *
     * @param bitmap
     * @return
     */
    private static boolean isEmptyBitmap(Bitmap bitmap) {
        return bitmap == null || bitmap.isRecycled() || bitmap.getWidth() == 0 || bitmap.getHeight() == 0;
    }

    private static boolean createFile(File file, boolean isDeleteOldFile) {
        if (file == null) return false;
        /*有无文件夹*/
        if (file.exists()) {
            /*是否删除旧文件*/
            if (isDeleteOldFile) {
                if (!file.delete()) return false;
            } else
                return file.isFile();
        }
        /*是否创建了父目录文件夹*/
        if (!createDir(file.getParentFile())) return false;
        try {
            return file.createNewFile();
        } catch (IOException e) {
            return false;
        }
    }

    private static boolean createDir(File file) {
        if (file == null) return false;
        if (file.exists())
            return file.isDirectory();
        else
            return file.mkdirs();
    }

    /**
     * 是否已授予权限
     *
     * @return
     */
    private static boolean isGranted() {
        return (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || PermissionUtils.isGranted(getPermissionArray()));
    }


    /**
     * 添加系统权限数组，便于rxPermission处理后续工作
     *
     * @return
     */
    public static String[] getPermissionArray() {
        String[] arr = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        return arr;
    }


    /**
     * 文件路径
     *
     * @return
     */
    public static String getImageFileDes() {
        StringBuilder builder = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath());
        builder.append(File.separator);
        builder.append("aerosense");
        builder.append(File.separator);
        builder.append("image");
        builder.append(File.separator);
        return builder.toString();
    }


    /**
     * 网络图片转bitmap
     *
     * @param httpUri
     * @return
     */
    public static Bitmap getBitmap(String httpUri) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(httpUri);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }


}
